import React, { memo, useState, useRef, useEffect } from "react";
import LoginWayOne from "@/components/loginCop/LoginWayOne";
import LoginWayTwo from "@/components/loginCop/LoginWayTwo";
import Mainlogin from "@/components/loginCop/mainlogin";
import PhoneLogin from "@/components/loginCop/phoneLogin";
import Register from "@/components/loginCop/register";
import { NavLink } from "react-router-dom";
import classnames from "classnames";
import { Modal } from "antd";
import { headerLinks, myLinks } from "@/services/local-data";
import { getSizeImage } from "@/utils/format-utils";
import { loginStatus, getMsgPrivate } from "@/services/login";
import Draggable from "react-draggable";
import Tips from "@/components/tips";
import { Badge, Avatar } from "antd";
import Search from "@/components/search";
import "./login.css";
import { removeLocalStroage } from "@/utils/localStorage";
import { Redirect } from "react-router-dom";

import { AppHeaderWrap, AppHeaderLeft, AppHeaderRight } from "./style";

export default memo(function AppHeader(props) {
  const [isLogin, setIsLogin] = useState(false);
  const [isChecks, setIsChecks] = useState(false);
  const [disabled, setDisabled] = useState(true);
  const [bounds, setBounds] = useState({
    left: 0,
    top: 0,
    bottom: 0,
    right: 0,
  });
  const [mainNum, setMainNum] = useState(0);
  const [userInfo, setUserInfo] = useState(false);
  const [msgNum, setMsgNum] = useState();
  const [closeW, setCloseW] = useState(0);

  const [status, setStatus] = useState(0);

  const draggleRef = useRef();
  const tipsRef = useRef();
  const timer = useRef(null);

  // 点击弹出弹窗并且刷新状态
  const loginbtn = () => {
    // history.go('/discover/recommend')
    setIsLogin(true);
    // clearInterval(timer.current)
    setStatus(1);
  };

  // 关闭弹窗结束计时
  useEffect(() => {
    if (!isLogin) {
      setStatus(0);
      setCloseW(0);
      // ("关闭了啊")
    } else {
      if (status === 1) {
        setCloseW(1);
      }
    }
    if (status !== 1) {
      setCloseW(0);
    }
    loginStatu();
  }, [isLogin, status]);

  // 查看登录状态
  async function loginStatu() {
    const a = await loginStatus();
    const b = await getMsgPrivate();
    setUserInfo(a);
    setMsgNum(b.newMsgCount);
  }

  const isCheck = (ischeck) => {
    setIsChecks(ischeck);
  };

  // 第一个登录弹窗页面 点击后去第二个登录页面
  const changeWayLogin = () => {
    setStatus(2);
  };

  const handleCancel = () => {
    if (status === 1) {
      setCloseW(0);
    } else {
      setIsChecks(false);
      setIsLogin(false);
    }
  };
  const closeLogin = () => {
    setIsChecks(false);
    setIsLogin(false);
  };
  // 点击返回第一个页面 二维码页面
  const changeCheck = () => {
    setStatus(1);
  };
  // 点击进入邮箱登录
  const changeModelToMail = () => {
    setMainNum(1);
    setStatus(3);
  };
  //返回第二个登录页面
  const otherWay = () => {
    setMainNum(0);
    setStatus(2);
  };

  //点击手机登录
  const phoneLogin = () => {
    if (isChecks) {
      setMainNum(2);
      setStatus(4);
    } else {
      tipsRef.current.style.display = "block";
      const timer = setTimeout(() => {
        tipsRef.current.style.display = "none";
        clearTimeout(timer);
      }, 2000);
    }
  };

  //点击注册
  const register = () => {
    if (isChecks) {
      setStatus(5);
      setMainNum(3);
    } else {
      // ("未勾选")
      tipsRef.current.style.display = "block";
      const timer = setTimeout(() => {
        tipsRef.current.style.display = "none";
        clearTimeout(timer);
      }, 2000);
    }
  };

  // 去第二个登录页面
  const phoneToOtherWay = () => {
    setMainNum(0);
    setStatus(2);
  };
  // 去第二个登录页面
  const zcToOtherWay = () => {
    setMainNum(0);
    setStatus(2);
  };

  // 去注册的页面
  const gotozcpages = () => {
    setMainNum(3);
    setStatus(5);
  };

  const onStart = (event, uiData) => {
    const { clientWidth, clientHeight } = window?.document?.documentElement;
    const targetRect = draggleRef?.current?.getBoundingClientRect();
    return setBounds({
      left: -targetRect?.left + uiData?.x,
      right: clientWidth - (targetRect?.right - uiData?.x),
      top: -targetRect?.top + uiData?.y,
      bottom: clientHeight - (targetRect?.bottom - uiData?.y),
    });
  };

  const showItem = (item, index) => {
    if (index < 3 || index > 4) {
      return (
        <NavLink to={item.link}>
          {item.title}
          <i className="sprite_01 icon"></i>
        </NavLink>
      );
    } else {
      return (
        <a href={item.link} target="_blank" rel="noopener noreferrer">
          {item.title}
        </a>
      );
    }
  };

  const closeBox = () => {
    setIsLogin(false);
  };
  if (userInfo) {
    window.localStorage.setItem("userInfo", JSON.stringify(userInfo));
  }

  const loginOut = (title) => {
    if (title === "退出") {
      window.localStorage.removeItem(userInfo);
      removeLocalStroage("token");
      removeLocalStroage("cookie");
      window.location.href = "/";
    }
  };

  const setStatusFunc = (num) => {
    setStatus(num);
  };
  return (
    <AppHeaderWrap>
      <div ref={tipsRef} className="tips">
        <Tips />
      </div>
      <div className="wrap-v1 content">
        <AppHeaderLeft>
          <a className="logo sprite_01">网易云音乐</a>
          <div className="select-header">
            {headerLinks.map((item, index) => {
              return (
                <div className={classnames("select-title")} key={item.title}>
                  {showItem(item, index)}
                </div>
              );
            })}
          </div>
        </AppHeaderLeft>
        <AppHeaderRight>
          <Search />
          <div className="create-centre">创作者中心</div>
          {userInfo.data ? (
            userInfo.data.profile ? (
              <div className="header-img">
                <Badge count={msgNum}>
                  <img
                    src={getSizeImage(userInfo.data.profile.avatarUrl, 30)}
                    alt=""
                  />
                </Badge>
                <ul>
                  {myLinks.map((item, index) => {
                    return (
                      <li key={item.icon}>
                        {item.title === "我的消息" ? (
                          <a href="#/">
                            <em>{item.title}</em>
                            <i className={item.icon}></i>
                            <i className="icon-num">
                              <em>{msgNum > 100 ? "99+" : msgNum}</em>
                            </i>
                          </a>
                        ) : (
                          <NavLink
                            onClick={(e) => loginOut(item.title)}
                            to={
                              item.title === "我的主页"
                                ? {
                                    pathname: "/user/home",
                                    search: "?id=" + userInfo.data.account.id,
                                  }
                                : item.title === "我的等级"
                                ? {
                                    pathname: "/my/level",
                                  }
                                : item.title === "VIP会员"
                                ? { pathname: "/member" }
                                : ""
                            }
                          >
                            <em>{item.title}</em>
                            <i className={item.icon}></i>
                          </NavLink>
                        )}
                      </li>
                    );
                  })}
                </ul>
              </div>
            ) : (
              <div onClick={loginbtn} className="login">
                登录
              </div>
            )
          ) : (
            <div onClick={loginbtn} className="login">
              登录
            </div>
          )}
        </AppHeaderRight>
      </div>
      <div className="underLine"></div>
      <div className="login-modal">
        <Modal
          title={
            <div
              style={{
                width: "100%",
                cursor: "move",
                color: "#fff",
                lineHeight: "38px",
                fontSize: "14px",
                paddingLeft: "10px",
              }}
              onMouseOver={() => {
                if (disabled) {
                  setDisabled(false);
                }
              }}
              onMouseOut={() => {
                setDisabled(true);
              }}
              onFocus={() => {}}
              onBlur={() => {}}
              // end
            >
              {mainNum == 0
                ? "登录"
                : mainNum == 1
                ? "邮箱登录"
                : mainNum == 2
                ? "手机号登录"
                : mainNum == 3
                ? "手机号注册"
                : ""}
            </div>
          }
          visible={isLogin}
          onCancel={handleCancel}
          footer={null}
          modalRender={(modal) => (
            <Draggable
              disabled={disabled}
              bounds={bounds}
              onStart={(event, uiData) => onStart(event, uiData)}
            >
              <div ref={draggleRef}>{modal}</div>
            </Draggable>
          )}
          getContainer={false}
          mask={false}
          maskClosable={false}
          centered={true}
        >
          <div className="modal-box-context">
            {status == 1 ? (
              <div>
                <LoginWayOne
                  setStatusFunc={setStatusFunc}
                  changeWayLogin={changeWayLogin}
                  closeW={closeW}
                  closeLogin={closeLogin}
                />
              </div>
            ) : status == 2 ? (
              <LoginWayTwo
                isCheck={isCheck}
                register={register}
                phoneLogin={phoneLogin}
                changeModelToMail={changeModelToMail}
                changeCheck={changeCheck}
              />
            ) : status == 3 ? (
              <Mainlogin otherWay={otherWay} />
            ) : status == 4 ? (
              <PhoneLogin
                gotozcpages={gotozcpages}
                close={closeBox}
                phoneToOtherWay={phoneToOtherWay}
              />
            ) : status == 5 ? (
              <Register zcToOtherWay={zcToOtherWay} />
            ) : (
              "1"
            )}
          </div>
        </Modal>
      </div>
    </AppHeaderWrap>
  );
});
